<template>
    <div class="content">
        <div class="head">
            <span class="head-title">一致性校验</span>
        </div>
        <div class="main">
            <div class="main-left">
                <div class="left-top">
                    <el-checkbox-group v-model="checkList">
                        <el-checkbox label="基准校验" value="基准校验"></el-checkbox>
                        <el-checkbox label="包材校验" value="包材校验"></el-checkbox>
                    </el-checkbox-group>
                </div>
                <div class="left-center">
                    <el-form
                        label-position="right"
                        label-width="100px"
                        ref="leftForm"
                        :model="leftForm"
                        :rules="leftFormRules"
                        size="small"
                        class="form-content"
                    >
                        <el-form-item label="备货单号" prop="stockUpOdd">
                            <el-input
                                v-model="leftForm.stockUpOdd"
                                placeholder="扫码输入"
                                ref="input0"
                                @keyup.enter.native="inputItem_enter($event, 'stockUpOdd')"
                                clearable
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="总数量">
                            <el-input
                                v-model.number="leftForm.totalNum"
                                placeholder="自动输入"
                                ref="input1"
                                @keyup.enter.native="inputItem_enter($event, 'totalNum')"
                                clearable
                                disabled
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="每箱数量" prop="quantityOfEachBox">
                            <el-input
                                v-model.number="leftForm.quantityOfEachBox"
                                placeholder="手动输入"
                                ref="input2"
                                @keyup.enter.native="inputItem_enter($event, 'eachBox')"
                                @input="leftForm.quantityOfEachBox = String(leftForm.quantityOfEachBox).replace(/\D/g,'')"
                                clearable
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="首样包材" prop="firstMatarials">
                            <el-input
                                v-model="leftForm.firstMatarials"
                                placeholder="扫码输入"
                                ref="input3"
                                :disabled="!checkList.includes('包材校验')"
                                @keyup.enter.native="inputItem_enter($event, 'firstMatarials')"
                                clearable
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="实物包材" prop="inKindMatarials">
                            <el-input
                                v-model="leftForm.inKindMatarials"
                                placeholder="扫码输入"
                                ref="input4"
                                :disabled="!checkList.includes('包材校验')"
                                @keyup.enter.native="inputItem_enter($event, 'inKindMatarials')"
                                clearable
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="实物21条码" prop="inKindBarCode_21">
                            <el-input
                                v-model="leftForm.inKindBarCode_21"
                                placeholder="扫码输入"
                                ref="input5"
                                @keyup.enter.native="inputItem_enter($event, 'inKindBarCode_21')"
                                clearable
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="外箱21条码" prop="outBoxBarCode_21">
                            <el-input
                                v-model="leftForm.outBoxBarCode_21"
                                placeholder="扫码输入"
                                ref="input6"
                                @keyup.enter.native="inputItem_enter($event, 'outBoxBarCode_21')"
                                clearable
                            ></el-input>
                        </el-form-item>
                    </el-form>
                    <el-button
                        type="primary"
                        size="small"
                        @click="startIsvalidate"
                        class="left-center-btn"
                        :disabled="!(inKindBarCode_21List.length > 0 && outBoxBarCode_21List.length > 0)"
                    >开始校验</el-button>
                </div>
                <div class="left-bottom">
                    <span class="bottom-info pass">PASS:{{ passRecord }}</span>
                    <span class="bottom-info fail">FAIL:{{ failRecord }}</span>
                </div>
            </div>
            <div class="main-right">
                <div class="main-icon">
                    <i style="cursor: pointer;" class="el-icon-setting" @click="setting_btn" title="设置"></i>
                </div>
                <div class="box">
                    <div class="right-box box1">
                        <div class="box-head">
                            <span class="head-title">实物条码:{{ inKindBarCode_21List.length }}</span>
                        </div>
                        <div class="box-main">
                            <div class="main-record record1">
                                <ul class="record-ul">
                                    <li
                                        class="ul-li"
                                        v-for="item,index in inKindBarCode_21List"
                                        :key="index"
                                    >
                                        <div class="li-item">
                                            <el-checkbox v-model="item.ischecked"></el-checkbox>
                                            <span class="item-code">{{ item.info }}</span>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="box-btns">
                            <el-button type="primary" size="mini" @click="clearAll_btn" :disabled="!(inKindBarCode_21List.length > 0)">全部清除</el-button>
                            <el-button type="info" size="mini" @click="clearSelected_btn" :disabled="!selectClearBtn">清除所选</el-button>
                        </div>
                    </div>
                    <div class="right-box box2">
                        <div class="box-head">
                            <span class="head-title">外箱条码:{{ outBoxBarCode_21List.length }}</span>
                        </div>
                        <div class="box-main">
                            <div class="main-record record2">
                                <ul class="record-ul">
                                    <li
                                        class="ul-li"
                                        v-for="item,index in outBoxBarCode_21List"
                                        :key="index"
                                    >
                                        <div class="li-item">
                                            <span class="item-code">{{ item }}</span>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="box-btns">
                            <el-button type="primary" size="mini" @click="clearAll_btn2" :disabled="!(outBoxBarCode_21List.length > 0)">全部清除</el-button>
                        </div>
                    </div>
                </div>
                <div class="btn">
                    <el-button type="primary" size="small" @click="exportRecords_btn">导出记录</el-button>
                </div>
            </div>
        </div>
        <!-- 校验结果的dialog -->
        <el-dialog title="校验提示" :visible.sync="resultDialog" width="20%" :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false" :modal="false" class="result-dialog">
            <div class="content">
                <div class="content-head">
                    <span class="head-tip pass">PASS:{{ this.passRecord }}</span>
                    <span class="head-tip fail">FAIL:{{ this.failRecord }}</span>
                </div>
                <div class="content-records">
                    <span class="records-info">{{ resultDialogTip }}</span>
                    <ul class="records-ul">
                        <li class="li-item" v-for="i in dialogList" :key="i + Math.random()">{{ i }}</li>
                    </ul>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="resultDialogConfirm_btn" size="small">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 锁屏 -->
        <el-dialog v-if="isLockScreen" title="等待质检员解锁后重新扫码" width="30%" :visible.sync="isLockScreen" :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false">
            <el-form :model="qualitingForm">
                <el-form-item label="账号:">
                    <el-input v-model="qualitingForm.username" :disabled="true" size="small" style="width:20vw;" placeholder="请输入账号"></el-input>
                </el-form-item>
                <el-form-item label="密码:">
                    <el-input v-model="qualitingForm.password" show-password size="small" ref="lockScreenInput" autofocus @keyup.enter.native="lockScreenConfirm_btn" style="width:20vw;" placeholder="请输入密码"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="lockScreenCancel_btn" size="small">重 置</el-button>
                <el-button type="primary" @click="lockScreenConfirm_btn" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 设置dialog -->
        <el-dialog title="提示" :visible.sync="settingFormVisible" width="30%">
            <div class="dialog-checkbox">
                <span class="checkbox-tip" style="margin-right:1vw;font-size: 14px;">选择产线:</span>
                <el-select v-model="lineCode" size="mini" placeholder="请选择">
                    <el-option v-for="item in lineCodeList" :key="item.id" :label="item.lineName" :value="item.lineCode"></el-option>
                </el-select>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="settingFormCancel" size="small">取 消</el-button>
                <el-button type="primary" @click="settingFormConfirm" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 导出记录dialog -->
        <el-dialog title="记录导出" :visible.sync="exportRecordsDialog" width="40%">
            <el-form :model="exportRecordsDialogForm">
                <el-form-item label="请选择产线" label-width="90px">
                    <el-select v-model="exportRecordsDialogForm.lineCode" size="small" style="width:70%;" placeholder="请选择">
                        <el-option v-for="item,index in lineCodeList" :label="item.lineName" :value="item.lineCode" :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="日期" label-width="90px">
                    <el-date-picker v-model="exportRecordsDialogForm.date" type="daterange" range-separator="至" start-placeholde="开始日期" end-placeholde="结束日期" value-format="yyyy-MM-dd" size="small" placeholder="选择日期" style="width:60%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="备货单" label-width="90px">
                    <el-input size="small" v-model="exportRecordsDialogForm.stockOrder" placeholder="请输入备货单" clearable style="width:60%;"></el-input>
                </el-form-item>
                <span class="item-span" style="font-size:12px;color:#c0c4cc;">注：产线、日期、备货单非必填项，导出的数据将根据以上约束进行过滤。</span>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="exportRecordsDialogCancel_btn">取 消</el-button>
                <el-button size="small" type="primary" :loading="exportBtnLoading" @click="exportRecordsDialogConfirm_btn">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { reqProductionOrderDetail, reqUnlockScreen, reqSaveInvalidateRecord, reqPassAndFailRecordCount, reqUserInfo, reqInvalidateInKindBarCode_21, reqExportConsistenceRecords, reqUploadConsistenceRecords, reqProductionIPBinds } from "@/api/project.js";
export default {
    name: "consistencyVerify",
    data() {
        const validate0 = (rule, value, callback) => {
            if(value.trim() === ''){
                callback(new Error('备货单不能为空'));
            } else {
                callback();
            }
        };
        const validate1 = (rule, value, callback) => {
            const totalNum = this.leftForm.totalNum;
            if(totalNum === ""){
                callback(new Error('总数量不能为空'));
            } else if(value.trim() === ''){
                callback(new Error('每箱数量不能为空'));
            } else if(parseInt(value) < 1 || parseInt(totalNum) < parseInt(value)) {
                callback(new Error('输入的每箱数量非法'));
            } else {
                callback();
            }
        };
        const validate2 = (rule, value, callback) => {
            const isOnValidate = this.checkList.includes("包材校验");
            if(isOnValidate){
                if(value.trim() === ''){
                    callback(new Error('首样包材不能为空'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validate3 = (rule, value, callback) => {
            const isOnValidate = this.checkList.includes("包材校验");
            const firstMatarials = this.leftForm.firstMatarials;
            if(isOnValidate){
                if(value.trim() === ''){
                    callback(new Error('实物包材不能为空'));
                } else if(value !== firstMatarials) {
                    callback(new Error('实物包材和首样包材不一致'));
                } else if(value === firstMatarials){
                    callback();
                }
            } else {
                callback();
            }
        };
        const validate4 = (rule, value, callback) => {
            const quantityOfEachBox = Number(this.leftForm.quantityOfEachBox);
            const inKindBarCode_21List = this.inKindBarCode_21List;
            if(value.trim() === '' && (quantityOfEachBox !== inKindBarCode_21List.length || quantityOfEachBox === 0)){
                callback(new Error('实物21条码不能为空'));
            } else {
                callback();
            }
        };
        const validate5 = (rule, value, callback) => {
            const quantityOfEachBox = Number(this.leftForm.quantityOfEachBox);
            const outBoxBarCode_21List = this.outBoxBarCode_21List;
            if(value.trim() === '' && !(outBoxBarCode_21List.length === 1 || (outBoxBarCode_21List.length === quantityOfEachBox && quantityOfEachBox !== 0))){
                callback(new Error('外箱21条码不能为空'));
            } else {
                callback();
            }
        };
        return {
            checkList: [],
            leftForm: {
                stockUpOdd: "",  //备货单号
                totalNum: "",
                quantityOfEachBox: "",
                firstMatarials: "",
                inKindMatarials: "",
                inKindBarCode_21: "",
                outBoxBarCode_21: ""
            },
            leftFormRules:{
                stockUpOdd:[{require:true,validator:validate0,trigger:"blur"}],
                quantityOfEachBox:[{require:true,validator:validate1,trigger:"blur"}],
                firstMatarials:[{require:true,validator:validate2,trigger:"blur"}],
                inKindMatarials:[{require:true,validator:validate3,trigger:"blur"}],
                inKindBarCode_21:[{require:true,validator:validate4,trigger:"blur"}],
                outBoxBarCode_21:[{require:true,validator:validate5,trigger:"blur"}]
            },
            inKindBarCode_21List: [],  //实物21条码数组
            outBoxBarCode_21List: [],  //外箱21条码数组
            currentInputFocus: 0,  //当前哪个输入框获取焦点
            timer: null,  //定时器实例
            isLockScreen: false,  //是否在锁屏状态
            qualitingForm: {
                username: "zhijianyuan",
                password: ""
            },
            passRecord: 0,  //成功记录
            failRecord: 0,
            failInKindBarCode_21List: [],  //校验失败的实物21条码
            failOutBoxBarCode_21List: [],  //校验失败的外箱21条码
            resultDialog:false,  //校验结果的dialog
            exportBtnLoading:false,
            exportRecordsDialog:false,  //导出记录dialog
            exportRecordsDialogForm:{
                lineCode:"",
                stockOrder:"",
                date:[]
            },
            lineCodeList:[],
            lineCode:"",
            settingFormVisible:false
        }
    },
    computed:{
        resultDialogTip(){
            if(this.failInKindBarCode_21List.length > 0) {
                return "以下实物21条码校验不通过:";
            } else if(this.failOutBoxBarCode_21List.length > 0) {
                return "以下外箱21条码校验不通过:";
            } else {
                return "全部校验通过";
            }
        },
        dialogList(){
            if(this.failInKindBarCode_21List.length > 0){
                return this.failInKindBarCode_21List;
            } else if(this.failOutBoxBarCode_21List.length > 0) {
                return this.failOutBoxBarCode_21List;
            } else {
                return [];
            }
        },
        selectClearBtn(){
            let list = this.inKindBarCode_21List.filter(item => {
                return item.ischecked === true;
            })
            return list.length > 0 ? true : false;
        }
    },
    mounted() {
        //页面一加载总数量输入框
        if (!this.isLockScreen) {
            this.$refs.input0.focus();
        }
        this.getProductionIPBinds();
        //获取校验成功和失败的数量
        //this.getRecordOfPassAndFail();
        //获取本地存储的相关数据
        const lineInfo = localStorage.getItem("lineInfo") === null ? "" : JSON.parse(localStorage.getItem("lineInfo"));
        //选择性打开dialog选择产线
        if (lineInfo === "") {
            this.settingFormVisible = true;
        } else {
            this.lineCode = lineInfo.lineCode;
        }
        //判断用户身份是否过期
        this.checkIsValidateUser();
        this.$refs.input0.focus();  //备货单输入框获取焦点
    },
    activated() {
        //组件从缓存中被加载
        //控制扫码枪读取备货单号
        // this.$refs.input0.focus();
    },
    deactivated() {
        //组件进入缓存状态
    },
    watch: {
        checkList: {
            handler(newVal, oldVal) {
                if(!this.checkList.includes("包材校验")){
                    this.leftForm.firstMatarials = "";
                    this.leftForm.inKindMatarials = "";
                }
                this.$refs.leftForm.clearValidate();
            }
        }
    },
    methods: {
        //7个输入框的keyup.enter事件
        inputItem_enter: function (event, progress) {
            switch (progress) {
                case 'stockUpOdd':
                    //校验备货单
                    this.invalidateInput0();
                    break;
                case 'totalNum':
                    break;
                case 'eachBox':
                    //校验每箱数量
                    this.invalidateInput2();
                    break;
                case 'firstMatarials':
                    //校验首样包材
                    this.invalidateInput3();
                    break;
                case 'inKindMatarials':
                    //校验实物包材
                    this.invalidateInput4();
                    break;
                case 'inKindBarCode_21':
                    this.detectionBarcode_21();
                    break;
                case 'outBoxBarCode_21':
                    this.detectionOuterBoxBarCodeEnter();
                    break;
                default:
                    break;
            }
        },
        //7个输入框的blur事件
        inputItem_blur(event, progress) {
            switch (progress) {
                case 'stockUpOdd':
                    //this.invalidateInput0();
                    break;
                case 'totalNum':
                    //this.invalidateInput1();
                    break;
                case 'eachBox':
                    //this.invalidateInput2();
                    break;
                case 'firstMatarials':
                    //this.invalidateInput3();
                    break;
                case 'inKindMatarials':
                    //this.invalidateInput4();
                    break;
                case 'inKindBarCode_21':
                    /* if(this.leftForm.inKindBarCode_21.trim() === "" && this.inKindBarCode_21List.length !== this.leftForm.quantityOfEachBox) {
                        this.$message({type:"warning",message:"实物21条码不能为空!"});
                    } */
                    break;
                case 'outBoxBarCode_21':
                    //this.invalidateInput6();
                    break;
                default:
                    break;
            }
        },
        //检测输入框输入停留时间跳转到下一个光标
        nextInputFocus(current, time) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            if (current !== 6) {
                this.timer = setTimeout(() => {
                    let input = 'input' + (current + 1);
                    this.$refs[input].focus();
                }, time);
            } else {
                //最后一个输入框:停留后让其失去焦点
                this.timer = setTimeout(() => {
                    let input = 'input' + (current);
                    this.$refs[input].blur();
                }, time);
            }
        },
        //检测到输入的是enter直接下一个输入框焦点
        nextInputFocus2(current) {
            if (current !== 6) {
                let input = 'input' + (current + 1);
                this.$refs[input].focus();
            } else {
                //最后一个输入框:停留后让其失去焦点
                let input = 'input' + (current);
                this.$refs[input].blur();
            }
        },
        //检测enter的输入录入实物21条码
        async detectionBarcode_21() {
            const barCode_21 = this.leftForm.inKindBarCode_21;
            const quantityOfEachBox = Number(this.leftForm.quantityOfEachBox);
            const inKindBarCode_21List = this.inKindBarCode_21List;
            if(!this.partFieldCheck(['stockUpOdd','quantityOfEachBox','firstMatarials','inKindMatarials','inKindBarCode_21'])){
                this.$message({type:"info",message:"请将表单填写完整"});
                return;
            }
            if (quantityOfEachBox > (inKindBarCode_21List.length + 1)) {
                if(inKindBarCode_21List.length === 0){
                    let result = this.checkList.includes("基准校验") ? await this.invalidateInput5(barCode_21) : true;
                    if (result) {
                        this.leftForm.inKindBarCode_21 = "";
                        this.inKindBarCode_21List.push({ info: barCode_21, ischecked: false });
                    } else {
                        this.$alert('实物21条码校验失败，检查后重试', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {}
                        });
                    }
                } else {
                    let lastCode_21 = inKindBarCode_21List[inKindBarCode_21List.length - 1].info;
                    if(lastCode_21.substring(2,10) === barCode_21.substring(2,10)){
                        let tmp = this.inKindBarCode_21List.findIndex(item => item.info === barCode_21);
                        if(tmp === -1){
                            let result = await this.invalidateInput5(barCode_21);
                            if(result){
                                this.inKindBarCode_21List.push({ info: barCode_21, ischecked: false });
                                this.leftForm.inKindBarCode_21 = "";
                                return;
                            } else {
                                this.$alert('实物21条码校验失败', '提示', {
                                    confirmButtonText: '确定',
                                    callback: action => {}
                                });
                            }
                        } else {
                            this.$alert('实物21条码出现重复', '提示', {
                                confirmButtonText: '确定',
                                callback: action => {}
                            });
                            return;
                        }
                    } else {
                        this.$alert('校验基准编码与上一个不同，请检查', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {}
                        });
                        return;
                    }
                }
            } else if (quantityOfEachBox === (this.inKindBarCode_21List.length + 1)) {
                if(quantityOfEachBox === 1){
                    let result = await this.invalidateInput5(barCode_21);
                    if(result){
                        this.inKindBarCode_21List.push({ info: barCode_21, ischecked: false });
                        this.$refs.input6.focus();
                        //记录光标指针
                        this.currentInputFocus = 6;
                        return ;
                    } else {
                        this.$alert('实物21条码校验失败', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {}
                        });
                        return;
                    }
                }
                let lastCode_21 = inKindBarCode_21List[inKindBarCode_21List.length - 1].info;
                if(lastCode_21.substring(2,10) === barCode_21.substring(2,10)){
                    let tmp = this.inKindBarCode_21List.findIndex(item => item.info === barCode_21);
                    if(tmp === -1){
                        let result = await this.invalidateInput5(barCode_21);
                        if(result){
                            this.inKindBarCode_21List.push({ info: barCode_21, ischecked: false });
                            this.$refs.input6.focus();
                            //记录光标指针
                            this.currentInputFocus = 6;
                            return ;
                        } else {
                            this.$alert('实物21条码校验失败', '提示', {
                                confirmButtonText: '确定',
                                callback: action => {}
                            });
                        }
                    } else {
                        return this.$alert('实物21条码出现重复', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {}
                        });
                    }
                } else {
                    this.$alert('校验基准编码以上一个不同，请检查', '提示', {
                        confirmButtonText: '确定',
                        callback: action => {}
                    });
                    return;
                }
            } else if (quantityOfEachBox < (this.inKindBarCode_21List.length + 1)) {
                this.$refs.input6.focus();
                //记录光标指针
                this.currentInputFocus = 6;
                if(this.leftForm.inKindBarCode_21 !== ""){
                    this.leftForm.inKindBarCode_21 = "";
                }
            }
        },
        //检测enter的录入外箱21条码
        detectionOuterBoxBarCodeEnter() {
            const code = this.leftForm.outBoxBarCode_21;
            const quantityOfEachBox = Number(this.leftForm.quantityOfEachBox);
            const outBoxBarCode_21List = this.outBoxBarCode_21List;
            if(!this.partFieldCheck(['stockUpOdd','quantityOfEachBox','firstMatarials','inKindMatarials','inKindBarCode_21','outBoxBarCode_21'])){
                this.$message({type:"info",message:"请将表单填写完整"});
                return;
            }
            if(code.trim() === ""){
                this.$message({type:"info",message:"外箱21码不能为空"});
                return;
            }
            //检测外箱21码是否有重复
            if(!this.outBoxBarCode_21List.includes(code)){
                if(outBoxBarCode_21List.length !== quantityOfEachBox){
                    this.outBoxBarCode_21List.push(code);
                    this.leftForm.outBoxBarCode_21 = "";
                    this.$refs.input6.focus();
                } else {
                    this.$alert("外箱21码数量超出实物21码数量", '提示', {
                        confirmButtonText: '确定',
                        callback: (action) => {}
                    })
                }
            } else {
                this.$alert("外箱21码出现重复", '提示', {
                    confirmButtonText: '确定',
                    callback: (action) => {}
                })
            }
        },
        //校验input0输入数据合法性
        async invalidateInput0() {
            //记录光标指针
            this.currentInputFocus = 0;
            const stockUpOdd = this.leftForm.stockUpOdd;
            if(!this.partFieldCheck(['stockUpOdd'])){
                this.$message({type:"info", message:"备货单不能为空"});
                return;
            }
            //请求该备货单的总数量
            reqProductionOrderDetail(stockUpOdd).then(response => {
                if (response.data.code === 200) {
                    const { data } = response.data
                    if (!data.pass) {
                        this.$refs.input0.blur();  //光标失去焦点
                        this.$alert(`<span style="color: black;font-size="16px">散件排产列表中找不到此备货单号:<span style="color: red">${stockUpOdd}</span>,请核对!</span>`, '提示', {
                            confirmButtonText: '确定',
                            dangerouslyUseHTMLString: true,
                            callback: action => {}
                        });
                        return;
                    }
                    this.leftForm.totalNum = response.data.data.productionOrderDetailDTO.totalQuantity;
                    this.$refs.input2.focus();
                    //记录光标指针
                    this.currentInputFocus = 2;
                }
            }).catch(error => {
                this.$message({ type: "warning", message: "请求备货单数量出错,请重试!"});
            })
        },
        invalidateInput1() {},
        invalidateInput2() {
            if(!this.partFieldCheck(['stockUpOdd','quantityOfEachBox'])){
                this.$message({type:"info",message:"请将表单填写完整"});
                return;
            }
            //每箱数量校验通过后 决定光标跳转位置
            if (this.checkList.includes('包材校验')) {
                this.$refs.input3.focus();
                //记录光标指针
                this.currentInputFocus = 3;
            } else {
                this.$refs.input5.focus();
                //记录光标指针
                this.currentInputFocus = 5;
            }
        },
        //校验input3输入数据合法性
        invalidateInput3() {
            if(!this.partFieldCheck(['stockUpOdd','quantityOfEachBox','firstMatarials'])){
                this.$message({type:"info",message:"请将表单填写完整"});
                return;
            }
            //光标跳转到input4
            this.$refs.input4.focus();
            //记录光标指针
            this.currentInputFocus = 4;
        },
        //校验input4输入数据合法性
        invalidateInput4() {
            if(!this.partFieldCheck(['stockUpOdd','quantityOfEachBox','firstMatarials','inKindMatarials'])){
                this.$message({type:"info",message:"请将表单填写完整"});
                return;
            }
            //光标跳转到输入框5
            this.$refs.input5.focus();
            //记录光标指针
            this.currentInputFocus = 5;
        },
        //是否开启基准校验input5输入数据合法性:实物21码
        async invalidateInput5(inKindBarCode_21) {
            if (this.checkList.includes("基准校验")) {
                let res = await reqInvalidateInKindBarCode_21(inKindBarCode_21);
                if (res.data.code === 200 && res.data.data.pass) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        },
        //上传本次检验记录
        async saveInvalidateRecord() {
            let stockOrder = this.leftForm.stockUpOdd;
            let inKinds = this.inKindBarCode_21List.map(item => {
                return item.info;
            })
            let outBoxs = this.outBoxBarCode_21List;
            let unPassCodes = this.failInKindBarCode_21List.length > 0 ? this.failInKindBarCode_21List : this.failOutBoxBarCode_21List;
            let checkResult = (this.failInKindBarCode_21List.length > 0 || this.failOutBoxBarCode_21List.length > 0) ? false : true;
            let res = await reqUploadConsistenceRecords(stockOrder,inKinds.toString(),outBoxs.toString(),unPassCodes.toString(),checkResult);
            if(res.data.code === 200){
                this.$message({type:"success",message:"记录上传成功!"});
            } else {
                this.$message({type:"success",message:"记录上传失败!"});
            }
            console.log("记录上传api",res);
        },
        //获取成功与失败的记录条数
        async getRecordOfPassAndFail() {
            let res = await reqPassAndFailRecordCount();
            if (res.data.data && res.data.code === 200) {
                this.passRecord = res.data.data.success;
                this.failRecord = res.data.data.fail;
            }
        },
        //格式化时间函数
        formateDate() {
            const date = new Date();
            let y = date.getFullYear();
            let m = date.getMonth() + 1;
            let d = date.getDate();
            let hour = date.getHours();
            let minutes = date.getMinutes();
            let second = date.getSeconds();
            return y + '-' + this.addZero(m) + '-' + this.addZero(d) + " " + this.addZero(hour) + ":" + this.addZero(minutes) + ":" + this.addZero(second);
        },
        //补零函数
        addZero(value) {
            return value > 9 ? value : ('0' + value);
        },
        //锁屏界面的重置和解锁按钮
        lockScreenCancel_btn() {
            this.qualitingForm.password = "";
            // this.isLockScreen = false;
            this.$refs.lockScreenInput.focus();
        },
        async lockScreenConfirm_btn() {
            const _this = this;
            if (this.qualitingForm.password === '') {
                return this.$message({ type: "warning", message: "请输入密码!" });
            }
            let res = await reqUnlockScreen(this.qualitingForm.password);
            if (res.data.data.id) {
                //质检员密码正确
                this.$message({ type: "success", message: "屏幕已解锁!" });
                //清空表单数据

                //跳转到数据一致性录入界面
                setTimeout(() => {
                    _this.isLockScreen = false;
                    _this.qualitingForm.password = "";
                    //打开扫码枪进行备货单的读取
                }, 500)
            } else {
                this.$message({ type: "error", message: "密码输入错误，请重试!" });
            }
            console.log('质检员输入密码解锁屏幕', res);
        },
        //判断当前用户身份是否过期
        async checkIsValidateUser() {
            let res = await reqUserInfo();
            let isExpired = res.data.data.isExpired;
            if (isExpired) {
                const routeList = this.$router.options.routes;
                let isHasSettingPermission = routeList.findIndex(item => item.path === '/setting');
                console.log('是否找到了该路由',isHasSettingPermission);
                if(isHasSettingPermission !== -1){
                    //跳转路由,打开重置密码框
                    this.$router.push({path:"/setting"});
                } else {
                    //无质检员设置权限
                    this.$alert('质检员身份过期，当前用户无质检员设置权限，请联系质检员进行密码重置！（质检员密码重置后刷新页面即可关闭此提示）', '提示', {
                        showConfirmButton:true,
                        showClose:false,
                        confirmButtonText: '刷新页面',
                        beforeClose: (action,instance,done) => {
                            //页面刷新
                            location.reload();
                        }
                    });
                }
            }
        },
        //开始校验按钮
        async startIsvalidate() {
            const _this = this;
            let isNeedLockScreen = false;  //校验后是否成功需要锁屏吗
            let outCode21List = this.outBoxBarCode_21List;
            let inCode21List = this.inKindBarCode_21List.map(item => {
                return item.info;
            })

            let eachBox = this.leftForm.quantityOfEachBox;  //每箱数量
            //外箱条码是有一个还是多个?
            //let reqCheckResult = 1;
            if (outCode21List.length === 1) {
                let pass = 0;
                for (let i = 0; i < eachBox; i++) {
                    if (this.checkList.includes("基准校验") && inCode21List[i] !== outCode21List[0]) {
                        isNeedLockScreen = true;
                    }
                    if (inCode21List[i] === outCode21List[0]) {
                        pass++;
                    }
                    if (inCode21List[i] !== outCode21List[0]) {
                        this.failInKindBarCode_21List.push(inCode21List[i]);  //收集失败的实物21条码
                    }
                    //判断检查结果：未开基准校验也能进行判断
                    // inCode21List[i] === outCode21List[0] ? reqCheckResult = 1 : reqCheckResult = 0;
                    // this.saveInvalidateRecord(inCode21List[i], outCode21List[0], reqCheckResult);  //上传当前校验记录
                    // if (i == eachBox - 1) {
                    //     this.$message({ type: "info", message: "校验记录上传中..." });
                    // }
                }
                this.passRecord = pass;
                this.failRecord = eachBox - pass;
            } else if (outCode21List.length > 1) {

                //检查多个外箱21码的情况下 其数量是否和实物21码是否一致
                if(outCode21List.length !== inCode21List.length){
                    this.$alert('外箱21码与实物21码数量不符,请检查!', '警告', {
                        confirmButtonText: '确定',
                        callback: action => {
                            //光标是否定在输入框6处?
                        }
                    });
                    return ;
                }

                //此处的failList是外箱不匹配的21码
                let failList = outCode21List.filter(item => {
                    if(inCode21List.includes(item)){
                        return false;
                    } else {
                        return true;
                    }
                })

                if (this.checkList.includes("基准校验") && failList.length > 0) {
                    isNeedLockScreen = true;
                }
                //此处已知成功和失败的数量
                this.passRecord = inCode21List.length - failList.length;
                this.failRecord = failList.length;
                this.failOutBoxBarCode_21List = failList;
            }

            //上传校验结果
            setTimeout(() => {
                this.saveInvalidateRecord();
            },800)

            //全部校验通过进行提示
            if (isNeedLockScreen) {
                //后续操作:锁屏
                this.controlLockScreen("实物21码与外箱21码出现不一致,即将锁屏!");
                return;
            }

            //打开校验结果框
            this.resultDialog = true;
        },
        //清除所有按钮
        clearAll_btn() {
            this.inKindBarCode_21List = [];
        },
        clearAll_btn2(){
            this.outBoxBarCode_21List = [];
        },
        //清除所选的按钮
        clearSelected_btn() {
            this.inKindBarCode_21List = this.inKindBarCode_21List.filter(item => {
                return item.ischecked === false;
            });
        },
        //控制锁屏
        controlLockScreen(info){
            this.$message({type:"warning",message:info});
            setTimeout(() => {
                this.isLockScreen = true;
            },300)
            setTimeout(() => {
                this.$refs.lockScreenInput.focus();
            },350)
        },
        //校验结果的dialog的确定按钮
        resultDialogConfirm_btn(){
            this.resultDialog = false;
            //判断数据的清空：出现fail则不清空任何数据，让其手动清除
            if(this.failInKindBarCode_21List.length > 0 || this.failOutBoxBarCode_21List.length > 0){
                //出现校验失败的:不作操作(要清空部分，否则会回显)
                this.failInKindBarCode_21List = [];
                this.failOutBoxBarCode_21List = [];
            } else {
                //全部校验成功
                //清空后三个输入框
                this.leftForm.inKindMatarials = "";
                this.leftForm.inKindBarCode_21 = "";
                this.leftForm.outBoxBarCode_21 = "";
                if (this.checkList.includes('包材校验')) {
                    this.$refs.input4.focus();
                    //记录光标指针
                    this.currentInputFocus = 4;
                } else {
                    this.$refs.input5.focus();
                    //记录光标指针
                    this.currentInputFocus = 5;
                }
                this.inKindBarCode_21List = [];
                this.outBoxBarCode_21List = [];
                // this.passRecord = 0;
                // this.failRecord = 0;
                this.failInKindBarCode_21List = [];
                this.failOutBoxBarCode_21List = [];
            }
        },
        //导出记录按钮
        async exportRecords_btn() {
            this.exportRecordsDialog = true;
        },
        //设置图标
        setting_btn(){
            this.settingFormVisible = true;
        },
        //导出记录dialog的按钮
        exportRecordsDialogCancel_btn(){
            this.exportRecordsDialog = false;
            this.exportRecordsDialogForm.lineCode = "";
            this.exportRecordsDialogForm.stockOrder = "";
            this.exportRecordsDialogForm.date = "";
        },
        async exportRecordsDialogConfirm_btn(){
            let { lineCode, stockOrder, date } = this.exportRecordsDialogForm;
            const params = {
                stockOrder:stockOrder,
                lineCode:lineCode,
                startDate:date[0],
                endDate:date[1]
            }
            this.exportBtnLoading = true;
            let res = await reqExportConsistenceRecords(params);
            if (res.status === 200) {
                let blob = res.data;
                let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
                const aLink = document.createElement('a');
                aLink.href = url;
                let timestamp = new Date().getTime();
                aLink.setAttribute('download', '一致性校验记录_' + timestamp);
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink);
                this.$message.success('导出成功');
                this.exportRecordsDialogCancel_btn();
                this.exportBtnLoading = false;
            } else {
                this.$message.error('导出失败,请重试');
                this.exportBtnLoading = false;
            }
        },
        //获取所有的产线列表接口
        async getProductionIPBinds() {
            let res = await reqProductionIPBinds();
            if (res.data.code === 200) {
                let list = res.data.data.map(item => {
                    return { id: item.id, lineCode: item.lineCode, lineIp: item.lineIp, lineName: item.lineName };
                })
                this.lineCodeList = list;
            }
            console.log('产线列表数据', res);
        },
        //settingDialog
        //设置确定按钮
        async settingFormConfirm() {
            if (this.lineCode === "") return;
            this.$message({ type: "success", message: "产线选择成功!" });
            setTimeout(() => {
                this.settingFormVisible = false;
            }, 200)
            //本地存储产线信息
            let lineInfo = this.lineCodeList.filter(item => item.lineCode === this.lineCode)[0];
            localStorage.setItem("lineInfo", JSON.stringify(lineInfo));
        },
        //设置取消按钮
        settingFormCancel() {
            this.settingFormVisible = false;
        },
        //表单校验
        globalCheck() {
            let checkResult = false;
            this.$refs.leftForm.validate((valid) => {
                checkResult = valid;
            });
            return checkResult;
        },
        partFieldCheck(fieldList){
            let checkedResultList = [];
            this.$refs.leftForm.validateField(fieldList,(result) => {
                if(result === ""){
                    checkedResultList.push(true);
                } else {
                    checkedResultList.push(false);
                }
            })
            return checkedResultList.every(e => e === true);
        },
    }
}
</script>

<style lang='scss' scoped>
.content {
    width: 100%;
    height: calc(100vh - 50px);
    user-select: none;
    .head {
        width: 100%;
        height: 6%;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        background-color: #02b2fd;
        font-size: 1.5vw;
        color: #fff;
    }
    .main {
        width: 100%;
        height: 94%;
        padding: 1% 4%;
        box-sizing: border-box;
        display: flex;
        .main-left {
            flex: 1;
            display: flex;
            flex-direction: column;
            .left-top {
                flex: 1;
            }
            .left-center {
                flex: 7;
                width: 70%;
                .left-center-btn {
                    margin: 2vh 1vw;
                }
            }
            .left-bottom {
                flex: 1;
                display: flex;
                .bottom-info {
                    margin: 0 8%;
                    font-size: 1.5vw;
                }
                .pass {
                    color: #83b336;
                }
                .fail {
                    color: #d9262c;
                }
            }
        }
        .main-right {
            flex: 1;
            display: flex;
            flex-direction: column;
            // align-items: center;
            .box{
                display: flex;
                .right-box {
                    margin: 0 2vw;
                    width: 20vw;
                    height: 75vh;
                    // border: 1px solid #dbdbdb;
                    .box-head {
                        width: 100%;
                        height: 6%;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        background-color: #02b2fd;
                        font-size: 1vw;
                        color: #fff;
                    }
                    .box-main {
                        width: 100%;
                        height: 90%;
                        padding: 1vh 1vw;
                        box-sizing: border-box;
                        display: flex;
                        overflow: auto;
                        background: #efefef;
                        .main-record {
                            width: 100%;
                            height: 100%;
                            display: flex;
                            .record-ul {
                                width: 100%;
                                height: 94%;
                                display: flex;
                                flex-direction: column;
                                list-style: none;
                                position: relative;
                                left: -2.2vw;
                                .ul-li {
                                    width: 100%;
                                    height: 5%;
                                    display: flex;
                                    margin-bottom: 1.5vh;
                                    .li-item {
                                        display: flex;
                                        align-items: center;
                                        .item-code {
                                            margin-left: 0.5vw;
                                            font-size: 1vw;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    .box-btns {
                        width: 100%;
                        margin: 1vh 0;
                        display: flex;
                        justify-content: space-around;
                    }
                }
            }
            .btn{
                position: relative;
                display: flex;
                justify-content: flex-end;
                left: 3vw;
                top:2vh;
                z-index: 999;
            }
            .main-icon{
                width: 100%;
                height: 2vh;
                display: flex;
                justify-content: flex-end;
            }
        }
    }
}

::v-deep .result-dialog{
    position: absolute;
    left:-50vw;
    top:-8vh;
    .content{
        width: 100%;
        height: 50vh;
        .content-head{
            width: 50%;
            height: 4vh;
            font-size: 1.5vw;
            line-height: 4vh;
            display: flex;
            justify-content: space-between;
            .pass{
                color: #008000;
            }
            .fail{
                color: #f00;
            }
        }
        .content-records{
            width:100%;
            height: 46vh;
            display: flex;
            flex-direction: column;
            border:1px dashed #9195a3;
            .records-info{
                font-size: 1.2vw;
            }
            .records-ul{
                width: 100%;
                height: 43vh;
                overflow: auto;
                .li-item{
                    font-size:1.5vw
                }
            }
        }
    }
}

::v-deep .el-message{
    z-index:9999;
}
::v-deep .el-dialog__body {
    font-size:1.5vw;
}
</style>